package com.peanut.web.controller;

import static springfox.documentation.schema.AlternateTypeRules.newRule;
import io.swagger.annotations.Api;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.WildcardType;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import com.fasterxml.classmate.TypeResolver;

/**
 * @author jzsong@uworks.cc
 */
@Configuration
@EnableWebMvc
@EnableSwagger2
public class SystemDocket {
  private Logger logger = LoggerFactory.getLogger(getClass());
  @Resource
  private TypeResolver typeResolver;

  private boolean isApi = true;

  /**
   * 生成API文档的入口.
   */
  @Bean
  public Docket generateApi() {
    logger.info("---------------------我是谁");
    // 可以根据配置决定不做任何API生成
    Docket docket = new Docket(DocumentationType.SWAGGER_2);
    if (!isApi) {
      return docket.select().apis(RequestHandlerSelectors.none()).build();
    }
    logger.info("初始化生成API文档......");
    // returns an instance of ApiSelectorBuilder
    ApiSelectorBuilder builder = docket.select();
    // 标示只有被 @Api 标注的才能生成API.
    builder.apis(RequestHandlerSelectors.withClassAnnotation(Api.class));
    builder.paths(PathSelectors.any());
    builder.build();
    docket.pathMapping("/");
    docket.genericModelSubstitutes(ResponseEntity.class);
    docket.alternateTypeRules(
        newRule(
            typeResolver.resolve(DeferredResult.class, typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
            typeResolver.resolve(WildcardType.class)));
    // 是否需要默认的response codes
    docket.useDefaultResponseMessages(false);

    docket.apiInfo(apiInfo());

    return docket;
  }

  private ApiInfo apiInfo() {
    return new ApiInfo("peanut_web系统接口", "peanut_web系统接口", "1.0.0", "", "", "", "");
  }

}
